package com.boyu.kindeditor;

import com.fasterxml.jackson.annotation.JsonInclude.Include;
import com.fasterxml.jackson.core.JsonParser.Feature;
import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.MapperFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

/**
 * json处理工具
 * @author huangchangan
 *
 */
public class JsonUtil {

	private static final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(JsonUtil.class);

	private static ObjectMapper objectMapper = new ObjectMapper();

	static {
		//支持单引号
		objectMapper.configure(Feature.ALLOW_SINGLE_QUOTES, true);
		// 设置输出时包含属性的风格
		objectMapper.configure(MapperFeature.USE_ANNOTATIONS, true);
		// 设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
		objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
		objectMapper.setSerializationInclusion(Include.NON_NULL);
		// 禁止使用int代表Enum的order()來反序列化Enum,非常危險
		objectMapper.configure(DeserializationFeature.FAIL_ON_NUMBERS_FOR_ENUMS, true);
		//空值转换-异常
		//objectMapper.configure(DeserializationFeature.ACCEPT_EMPTY_STRING_AS_NULL_OBJECT, true);
		//转义字符-异常
		objectMapper.configure(Feature.ALLOW_UNQUOTED_CONTROL_CHARS, true);
	}

	public static <T> T parse(String jsonStr, Class<T> valueType) {
		try {
			return objectMapper.readValue(jsonStr, valueType);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	/**
	 * 泛型反序列化 ,如List<T>,Map<K,V>
	 * @param jsonStr
	 * @param collectionClass
	 * @param elementClasses
	 * @return
	 */
	public static <T> T parse(String jsonStr, Class<T> collectionClass, Class<?>... elementClasses) {
		try {
			JavaType valueType = getCollectionType(collectionClass, elementClasses);
			return objectMapper.readValue(jsonStr, valueType);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	public static String parse(Object obj) {
		try {
			return objectMapper.writeValueAsString(obj);
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return null;
	}

	/**   
	 * 获取泛型的Collection Type  
	* @param collectionClass 泛型的Collection   
	  * @param elementClasses 元素类   
	  * @return JavaType Java类型   
	  * @since 1.0   
	 */
	public static JavaType getCollectionType(Class<?> collectionClass, Class<?>... elementClasses) {
		return objectMapper.getTypeFactory().constructParametricType(collectionClass, elementClasses);
	}

}
